import java.sql.*;

public class ArticleTree {
	public static void main(String[] args) {
		new ArticleTree().show();
	}

	public void show() {
		Connection conn = null;
		Statement sta = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/bbs?user=root&password=123456");
			sta = conn.createStatement();
			rs = sta.executeQuery("select * from article where pid = 0");
			while(rs.next()) {
				System.out.println(rs.getString("cont"));
				tree(rs.getInt("id"), conn, 1);
			}
		} catch(ClassNotFoundException e) { 
			e.printStackTrace();
		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(sta != null) {
					sta.close();
					sta = null;
				}
				if(rs != null) {
					rs.close();
					rs = null;
				}
			} catch(SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void tree(int id, Connection conn, int level) {
		Statement sta = null;
		ResultSet rs = null;
		
		StringBuffer preStr = new StringBuffer("");
		
		for(int i = 0; i < level; i++) {
			preStr.append("	");
		}
		
		try {
			sta = conn.createStatement();
			rs = sta.executeQuery("select * from article where pid = " + id);
			while(rs.next()) {
				System.out.println(preStr + rs.getString("cont"));
				tree(rs.getInt("id"), conn, level + 1);
			}
		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(sta != null) {
					sta.close();
					sta = null;
				}
				if(rs != null) {
					rs.close();
					rs = null;
				}
			} catch(SQLException e) {
				e.printStackTrace();
			}
			
		}
	}
}

